package org.example.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.dao.RouterRuleDao;
import org.example.dao.RouterparametersDao;
import org.example.po.Routerparameters;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

@Deprecated
@Aspect
public class GlobalOperationAspect {
    @Resource
    private RouterparametersDao routerparametersDao;

    @Pointcut("@annotation(org.example.annotation.GlobalInterceptor)")
    private void requestInterceptor() {
    }


    @Around("requestInterceptor()")
    public Object checkRouter(ProceedingJoinPoint point){
        Object target = point.getTarget();
        Object invo = point.getArgs()[0];
        String methodName = point.getSignature().getName();
        String tradeCode = methodName.substring(2);
        QueryWrapper<Routerparameters> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rulename",tradeCode);
        List<Routerparameters> list = routerparametersDao.selectList(queryWrapper);
        PriorityQueue<Routerparameters> priorityQueue = new PriorityQueue<>(new Comparator<Routerparameters>() {
            @Override
            public int compare(Routerparameters o1, Routerparameters o2) {
                return Integer.parseInt(o1.getPriority()) - Integer.parseInt(o2.getPriority());
            }
        });
        Field[] fields = invo.getClass().getDeclaredFields();
        priorityQueue.addAll(list);
        boolean isRouted = false;
        while(!priorityQueue.isEmpty()){
            Routerparameters routerparameters = priorityQueue.poll();
            String field = routerparameters.getRuleid();
            String value = routerparameters.getRulevalue();
            for (Field objectField : fields) {
                if(field.equals(objectField)){
                    try {
                        Object o = objectField.get(invo);
                        if(o != null && o.toString().equals(value)){
                            //todo
                            isRouted = true;
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        if (isRouted == false){
            try {
                point.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
